<template>
  <div id="register">
    <form>
      <label for="username">
        <input type="text" class="input" id="username" placeholder="姓名"
          :class="{ noborder: checkUser }"
          v-model="model.user"
          @focus.stop="focus = 1"
          @blur="focus = 0" 
          autocomplete="off"/>
        <em v-show="focus == 1 || !checkUser">*用户名不能为空且只能由字母、数字、下划线组成</em>
        <em v-show="req===false&&focus!=1">*该用户名已被使用</em>
      </label>
      <label for="tel">
        <input type="text" class="input" id="tel" placeholder="手机号"
          :class="{ noborder: checkTel }"
          v-model="model.tel"
          @focus.stop="focus = 2"
          @blur="focus = 0" 
          autocomplete="off"/>
        <em v-show="focus == 2 || !checkTel">*手机号全为数字</em>
      </label>
      <label for="pwd">
        <input type="password" class="input" id="pwd" placeholder="密码（不少于6位）"
          v-model="model.pwd"
          @focus.stop="focus = 3"
          @blur="focus = 0" />
          <em v-show="focus == 3 || !checkPwd">*密码不能小于6位</em>
      </label>
      <div class="button_wrap">
        <button class="submit" @click.prevent="addToSql">
          <span v-show="!result">注册速讯</span>
          <span v-if="req" v-show="result">注册成功</span>
          <span v-else v-show="result">重新注册</span>
          <i class="fa fa-spinner fa-spin" v-show="icon"></i>
          <i class="fa fa-check" v-if="req" v-show="result"></i>
          <i class="fa fa-times" v-else v-show="result"></i>
        </button>
      </div>
    </form>
  </div>
</template>

<script>
export default {
  name: 'register',
  data() {
    return {
      focus: 0,
      model: {
        user: '',
        tel: '',
        pwd: ''
      },
      checkUser: true,
      checkTel: true,
      checkPwd: true,
      icon: false, //控制转动图标显示
      result: false, //是否发送注册请求
      req: '' // 注册响应是否成功
    }
  },
  methods: {
    addToSql() {
      this.checkUser = (this.model.user == '' || /\W/g.test(this.model.user)) ? false : true
      this.checkTel = (this.model.tel == '' || /\D/g.test(this.model.tel)) ? false : true
      this.checkPwd = (this.model.pwd.length < 6) ? false : true

      // 如果三条注册项都验证成功，则发送注册请求
      if(this.checkUser&&this.checkTel&&this.checkPwd){
        // 重置注册按钮状态
        this.icon = true
        this.result = false
        this.req = ''

        // 一段时间后，发送注册请求
        setTimeout(() => {
          this.icon = false
          this.$store.dispatch('register', this.model)
          this.result = true

          // 如果注册成功,则修改为注册成功按钮状态
          if(sessionStorage.register && sessionStorage.register == 1) {
            this.req = true
            // 重置用户注册信息
            this.model.user = ''
            this.model.tel = ''
            this.model.pwd = ''
          } else {
            // 失败则修改注册失败的按钮状态
            this.req = false
          }
        },1000)
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import url('../assets/css/login.less');
</style>